<template>
  <div class="project-settings">
    <el-form 
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
    >
      <!-- 基本设置 -->
      <div class="form-section">
        <h3>基本设置</h3>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        
        <el-form-item label="项目描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="Git仓库地址" prop="repositoryUrl">
          <el-input v-model="form.repositoryUrl" />
        </el-form-item>
      </div>

      <!-- 部署配置 -->
      <div class="form-section">
        <h3>部署配置</h3>
        <el-form-item label="部署分支" prop="deploymentConfig.branch">
          <el-input 
            v-model="form.deploymentConfig.branch" 
            placeholder="master"
          />
        </el-form-item>

        <el-form-item label="构建命令" prop="deploymentConfig.buildCommand">
          <el-input 
            v-model="form.deploymentConfig.buildCommand" 
            placeholder="npm run build"
          />
        </el-form-item>

        <el-form-item label="输出目录" prop="deploymentConfig.outputDir">
          <el-input 
            v-model="form.deploymentConfig.outputDir" 
            placeholder="dist"
          />
        </el-form-item>
      </div>

      <!-- 服务器配置 -->
      <div class="form-section">
        <h3>服务器配置</h3>
        <el-form-item label="服务器地址" prop="deploymentConfig.serverConfig.host">
          <el-input 
            v-model="form.deploymentConfig.serverConfig.host" 
            placeholder="例如：123.456.789.0"
          />
        </el-form-item>

        <el-form-item label="SSH端口" prop="deploymentConfig.serverConfig.port">
          <el-input-number 
            v-model="form.deploymentConfig.serverConfig.port" 
            :min="1"
            :max="65535"
            placeholder="22"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="deploymentConfig.serverConfig.username">
          <el-input 
            v-model="form.deploymentConfig.serverConfig.username" 
            placeholder="root"
          />
        </el-form-item>

        <el-form-item label="认证方式">
          <el-radio-group v-model="form.deploymentConfig.serverConfig.authType">
            <el-radio :value="'password'">密码认证</el-radio>
            <el-radio :value="'privateKey'">SSH密钥</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="form.deploymentConfig.serverConfig.authType === 'password'">
          <el-form-item label="密码" prop="deploymentConfig.serverConfig.password">
            <el-input 
              v-model="form.deploymentConfig.serverConfig.password"
              type="password"
              show-password
              placeholder="输入服务器密码"
            />
          </el-form-item>
        </template>

        <template v-else>
          <el-form-item label="SSH私钥" prop="deploymentConfig.serverConfig.privateKey">
            <el-input 
              v-model="form.deploymentConfig.serverConfig.privateKey"
              type="textarea"
              :rows="8"
              placeholder="-----BEGIN RSA PRIVATE KEY-----
                         ...
         -----END RSA PRIVATE KEY-----"
            />
          </el-form-item>
          <el-form-item label="密钥密码（如果有）">
            <el-input 
              v-model="form.deploymentConfig.serverConfig.passphrase"
              type="password"
              show-password
              placeholder="可选"
            />
          </el-form-item>
        </template>

        <el-form-item label="部署路径" prop="deploymentConfig.serverConfig.path">
          <el-input 
            v-model="form.deploymentConfig.serverConfig.path" 
            placeholder="/var/www/html"
          />
        </el-form-item>

        <div class="server-actions">
          <el-button 
            type="primary" 
            plain 
            @click="testConnection"
            :loading="testing"
          >
            {{ testing ? '测试中...' : '测试连接' }}
          </el-button>
        </div>

        <div v-if="connectionTestResult" 
             :class="['test-result', connectionTestResult.success ? 'success' : 'error']">
          {{ connectionTestResult.message }}
        </div>
      </div>

      <!-- 表单操作 -->
      <div class="form-actions">
        <el-button @click="$emit('cancel')">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存更改</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { projectApi } from '../api/project'

const props = defineProps({
  project: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['save', 'cancel'])

const formRef = ref(null)
const testing = ref(false)
const connectionTestResult = ref(null)

const form = ref({
  name: '',
  description: '',
  repositoryUrl: '',
  deploymentConfig: {
    branch: '',
    buildCommand: '',
    outputDir: '',
    serverConfig: {
      host: '',
      port: 22,
      username: '',
      authType: 'password',
      password: '',
      privateKey: '',
      passphrase: '',
      path: ''
    }
  }
})

const rules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  repositoryUrl: [
    { required: true, message: '请输入Git仓库地址', trigger: 'blur' }
  ],
  'deploymentConfig.serverConfig.host': [
    { required: true, message: '请输入服务器地址', trigger: 'blur' }
  ],
  'deploymentConfig.serverConfig.username': [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  'deploymentConfig.serverConfig.path': [
    { required: true, message: '请输入部署路径', trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    emit('save', form.value)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const testConnection = async () => {
  try {
    testing.value = true
    connectionTestResult.value = null
    const result = await projectApi.testServerConnection(form.value.deploymentConfig.serverConfig)
    connectionTestResult.value = result
    ElMessage.success('连接测试成功')
  } catch (error) {
    connectionTestResult.value = {
      success: false,
      message: error.response?.data?.message || '连接测试失败'
    }
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

onMounted(() => {
  // 初始化表单数据
  form.value = {
    ...props.project,
    deploymentConfig: {
      ...props.project.deploymentConfig,
      serverConfig: {
        ...props.project.deploymentConfig?.serverConfig
      }
    }
  }
})
</script>

<style scoped>
.project-settings {
  padding: 1rem;
}

.form-section {
  margin-bottom: 2rem;
}

.form-section h3 {
  margin-bottom: 1rem;
  color: #333;
  font-size: 1.1rem;
}

.server-actions {
  margin-top: 1rem;
}

.test-result {
  margin-top: 0.5rem;
  padding: 0.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
}

.test-result.success {
  background: #e8f5e9;
  color: #2e7d32;
}

.test-result.error {
  background: #ffebee;
  color: #c62828;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
  padding-top: 1rem;
  border-top: 1px solid #eee;
}
</style> 